package com.tyqx.hashchainbiz.controller.wx;


import com.tyqx.hashchainbean.module.WxUserInfo;
import com.tyqx.hashchainbean.vo.WxUserStatusVO;
import com.tyqx.hashchainbiz.service.HashChainPasswordService;
import com.tyqx.hashchainbiz.service.WxUserInfoService;
import com.tyqx.hashchainutil.common.ChainCode;
import com.tyqx.hashchainutil.common.CreateWallet;
import hashchainutil.common.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx/userInfo")
@CrossOrigin
public class WxUserInfoController {


    @Resource
    private WxUserInfoService wxUserInfoService;

    @Resource
    private HashChainPasswordService hashChainPasswordService;

    // yingpi login
    @RequestMapping(value = "/decodeUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public Map decodeUserInfo(String encryptedData, String iv, String code) throws JSONException {
        Map map = new HashMap();
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return map;
        }
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "wxa4cc98280ee80ec4";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "9c80eac087d677db332ceb1a88601999";
        //授权（必填）
        String grant_type = "authorization_code";


        //向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = new JSONObject(sr);
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");

        //对encryptedData加密数据进行AES解密
        try {
            String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");

                JSONObject userInfoJSON = new JSONObject(result);
                String openId = userInfoJSON.getString("openId");
                String nickName = userInfoJSON.getString("nickName");
                String gender = userInfoJSON.getString("gender");
                String city = userInfoJSON.getString("city");
                String province = userInfoJSON.getString("province");
                String country = userInfoJSON.getString("country");
                String avatarUrl = userInfoJSON.getString("avatarUrl");
                Map userInfo = new HashMap();
                userInfo.put("openId", openId);
                userInfo.put("nickName", nickName);
                userInfo.put("gender", gender);
                userInfo.put("city", city);
                userInfo.put("province", province);
                userInfo.put("country", country);
                userInfo.put("avatarUrl", avatarUrl);
                map.put("userInfo", userInfo);

                WxUserInfo wxUserInfo1=wxUserInfoService.queryWxUserInfoByOpenId(openId);
                if(EmptyUtils.isEmpty(wxUserInfo1)) {
                    WxUserInfo wxUserInfo = new WxUserInfo();
                    wxUserInfo.setOpenId(openId);
                    wxUserInfo.setNickName(nickName);
                    wxUserInfo.setGender(gender);
                    wxUserInfo.setCity(city);
                    wxUserInfo.setWxProvince(province);
                    wxUserInfo.setCountry(country);
                    Date currentDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date createTime = sdf.parse(sdf.format(currentDate));
                    wxUserInfo.setCreateDate(createTime);
                    wxUserInfo.setType(0);
                    wxUserInfoService.insertWxUserInfo(wxUserInfo);
                }
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");
        return map;

    }

    //zhaopi login
    @RequestMapping(value = "/decodeRecruitUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public Map decodeRecruitUserInfo(String encryptedData, String iv, String code) throws JSONException {
        Map map = new HashMap();
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return map;
        }
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "wx9041834b7c7c0156";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "12175922b8c013fb42a5510a00680c2b";
        //授权（必填）
        String grant_type = "authorization_code";


        //向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = new JSONObject(sr);
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");

        //对encryptedData加密数据进行AES解密
        try {
            String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");

                JSONObject userInfoJSON = new JSONObject(result);
                String openId = userInfoJSON.getString("openId");
                String nickName = userInfoJSON.getString("nickName");
                String gender = userInfoJSON.getString("gender");
                String city = userInfoJSON.getString("city");
                String province = userInfoJSON.getString("province");
                String country = userInfoJSON.getString("country");
                String avatarUrl = userInfoJSON.getString("avatarUrl");
                Map userInfo = new HashMap();
                userInfo.put("openId", openId);
                userInfo.put("nickName", nickName);
                userInfo.put("gender", gender);
                userInfo.put("city", city);
                userInfo.put("province", province);
                userInfo.put("country", country);
                userInfo.put("avatarUrl", avatarUrl);
                map.put("userInfo", userInfo);

                WxUserInfo wxUserInfo1=wxUserInfoService.queryWxUserInfoByOpenId(openId);
                if(EmptyUtils.isEmpty(wxUserInfo1)) {
                    WxUserInfo wxUserInfo = new WxUserInfo();
                    wxUserInfo.setOpenId(openId);
                    wxUserInfo.setNickName(nickName);
                    wxUserInfo.setGender(gender);
                    wxUserInfo.setCity(city);
                    wxUserInfo.setWxProvince(province);
                    wxUserInfo.setCountry(country);
                    Date currentDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date createTime = sdf.parse(sdf.format(currentDate));
                    wxUserInfo.setCreateDate(createTime);
                    wxUserInfo.setType(1);
                    wxUserInfoService.insertWxUserInfo(wxUserInfo);
                }
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");
        return map;

    }


    @RequestMapping(value = "/auditUnitUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public Map auditUnitUserInfo(String encryptedData, String iv, String code) throws JSONException {
        Map map = new HashMap();
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return map;
        }




        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "wx35768bac2ca3d350";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "c6effc1d864c77a579e31af4d27279b2";
        //授权（必填）
        String grant_type = "authorization_code";


        //向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = new JSONObject(sr);
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");

        //对encryptedData加密数据进行AES解密
        try {
            String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");

                JSONObject userInfoJSON = new JSONObject(result);
                String openId = userInfoJSON.getString("openId");
                String nickName = userInfoJSON.getString("nickName");
                String gender = userInfoJSON.getString("gender");
                String city = userInfoJSON.getString("city");
                String province = userInfoJSON.getString("province");
                String country = userInfoJSON.getString("country");
                String avatarUrl = userInfoJSON.getString("avatarUrl");
                Map userInfo = new HashMap();
                userInfo.put("openId", openId);
                userInfo.put("nickName", nickName);
                userInfo.put("gender", gender);
                userInfo.put("city", city);
                userInfo.put("province", province);
                userInfo.put("country", country);
                userInfo.put("avatarUrl", avatarUrl);
                map.put("userInfo", userInfo);

                WxUserInfo wxUserInfo1=wxUserInfoService.queryWxUserInfoByOpenId(openId);
                if(EmptyUtils.isEmpty(wxUserInfo1)) {
                    WxUserInfo wxUserInfo = new WxUserInfo();
                    wxUserInfo.setOpenId(openId);
                    wxUserInfo.setNickName(nickName);
                    wxUserInfo.setGender(gender);
                    wxUserInfo.setCity(city);
                    wxUserInfo.setWxProvince(province);
                    wxUserInfo.setCountry(country);
                    Date currentDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date createTime = sdf.parse(sdf.format(currentDate));
                    wxUserInfo.setCreateDate(createTime);
                    wxUserInfo.setType(2);
                    wxUserInfo.setStatus(0);
                    map.put("wxUserInfoStatus", 0);

                    /*createWallet.addPeerOrgUser(COMPOSE_PROJECT_NAME,caIndex,openId,orgIndex,openId);
                    ChainCode chainCode=new ChainCode();
                    chainCode.setBalance(COMPOSE_PROJECT_NAME,openId,1000,channelName,chaincodeName,"setBalance");*/
                    wxUserInfo.setIfLoginBlockChain(1);
                    wxUserInfoService.insertWxUserInfo(wxUserInfo);
                }else{
                    map.put("wxUserInfoStatus", wxUserInfo1.getStatus());
                }

                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");
        return map;

    }


    @RequestMapping(value = "/underInvestigation", method = RequestMethod.GET)
    @ResponseBody
    public Map underInvestigation(String encryptedData, String iv, String code) throws JSONException {
        Map map = new HashMap();
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return map;
        }

        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "wxfd4b7391b0a55d5a";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "8ac86b89bedcef3653ad7f56c1ebddb4";
        //授权（必填）
        String grant_type = "authorization_code";


        //向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = new JSONObject(sr);
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");

        //对encryptedData加密数据进行AES解密
        try {
            String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");

                JSONObject userInfoJSON = new JSONObject(result);
                String openId = userInfoJSON.getString("openId");
                String nickName = userInfoJSON.getString("nickName");
                String gender = userInfoJSON.getString("gender");
                String city = userInfoJSON.getString("city");
                String province = userInfoJSON.getString("province");
                String country = userInfoJSON.getString("country");
                String avatarUrl = userInfoJSON.getString("avatarUrl");
                Map userInfo = new HashMap();
                userInfo.put("openId", openId);
                userInfo.put("nickName", nickName);
                userInfo.put("gender", gender);
                userInfo.put("city", city);
                userInfo.put("province", province);
                userInfo.put("country", country);
                userInfo.put("avatarUrl", avatarUrl);
                map.put("userInfo", userInfo);

                WxUserInfo wxUserInfo1=wxUserInfoService.queryWxUserInfoByOpenId(openId);
                if(EmptyUtils.isEmpty(wxUserInfo1)) {
                    WxUserInfo wxUserInfo = new WxUserInfo();
                    wxUserInfo.setOpenId(openId);
                    wxUserInfo.setNickName(nickName);
                    wxUserInfo.setGender(gender);
                    wxUserInfo.setCity(city);
                    wxUserInfo.setWxProvince(province);
                    wxUserInfo.setCountry(country);
                    Date currentDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date createTime = sdf.parse(sdf.format(currentDate));
                    wxUserInfo.setCreateDate(createTime);
                    wxUserInfo.setType(3);
                    wxUserInfo.setStatus(0);
                    map.put("wxUserInfoStatus", 0);

                    /*createWallet.addPeerOrgUser(COMPOSE_PROJECT_NAME,caIndex,openId,orgIndex,openId);
                    ChainCode chainCode=new ChainCode();
                    chainCode.setBalance(COMPOSE_PROJECT_NAME,openId,1000,channelName,chaincodeName,"setBalance");*/
                    wxUserInfo.setIfLoginBlockChain(1);
                    wxUserInfoService.insertWxUserInfo(wxUserInfo);
                }else{
                    map.put("wxUserInfoStatus", wxUserInfo1.getStatus());
                }

                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");
        return map;

    }

    @RequestMapping(value = "/updateWxUserStatusByOpenId", method = RequestMethod.POST)
    @ResponseBody
    public Dto updateWxUserStatusByOpenId(@RequestBody WxUserStatusVO wxUserStatusVO) throws ParseException {
        String message = "";
        if(EmptyUtils.isNotEmpty(wxUserStatusVO.getStatus())&& EmptyUtils.isNotEmpty(wxUserStatusVO.getOpenId())){
            int flag = wxUserInfoService.updateStatus(wxUserStatusVO.getStatus(), wxUserStatusVO.getOpenId());
            if(flag>0){
                message = "修改公司用户状态成功";
            }else{
                message =  "修改公司用户状态失败";
            }
        }else{
            message = "信息为空，修改失败";
        }
        return DtoUtil.returnSuccess(message);
    }
}
